<template>
  <div>
    <h2>Login</h2>

    <el-form :model="form" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px">
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-form-item>
        <div class="div1">
          <div class="left"><el-button @click="goTo('/user/register')">还没有账号？去注册</el-button></div>
          <div class="right"><el-button type="primary" @click="submitForm">确认</el-button></div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import axios from 'axios';
import { FormRules } from 'element-plus';
import { useGoTo } from '@/hooks/useGoTo';
import { useUserStore } from '@/stores/userStore'; // 引入 Pinia store
import { ElMessage } from 'element-plus';

const { goTo } = useGoTo();
const userStore = useUserStore(); // 使用 Pinia store

const form = reactive({
  email: '',
  password: '',
});

const formRef = ref(null);

const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
  ],
};

const submitForm = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        onSubmit();
      } else {
        ElMessage({
          message: '验证失败',
          grouping: true,
          type: 'error',
        });
        return false;
      }
    });
  }
};

async function onSubmit() {
  try {
    const response = await axios.post('/api/user/login', {
      email: form.email,
      password: form.password,
    });

    if (response.data.code === '200') {
      ElMessage({
        message: '登录成功',
        type: 'success',
      });

      // 使用 Pinia store 更新用户信息
      userStore.setUser(response.data.data);

      // 导航到新页面
      goTo('/user/info');
    } else if (response.data.code === '-1') {
      ElMessage({
        message: response.data.msg,
        type: 'error',
      });
    }

    console.log(response.data);
  } catch (error) {
    console.error(error);
    ElMessage({
      message: '登录失败，请重试',
      type: 'error',
    });
  }
}
</script>

<style scoped>
.div1 {
  width: 1200px;
  height: 70px;
  display: flex;
  justify-content: space-between;
}

.left {
  display: flex;
  justify-content: center;
  align-items: center;
}

.right {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>